using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.AddressableAssets.Settings;
using UnityEngine;

namespace AddressablesTool
{
    /// <summary>
    /// Prefab依赖右键菜单
    /// </summary>
    public static class PrefabDependencyMenu
    {
        // [MenuItem("Assets/Addressables/Add Prefab and Dependencies to Group", false, 30)]
        [MenuItem("Assets/Addressables/添加到组", false, 30)]
        public static void AddPrefabAndDependenciesToGroup()
        {
            // 检查Addressables设置
            if (!AddressablesGroupManager.HasAddressablesSettings())
            {
                if (EditorUtility.DisplayDialog("Addressables设置未找到", "是否创建Addressables设置？", "是", "否"))
                {
                    CreateAddressablesSettings();
                }

                return;
            }

            var selectedPrefabs = GetSelectedPrefabs();
            if (selectedPrefabs.Count == 0)
            {
                EditorUtility.DisplayDialog("提示", "请选中一个或多个Prefab", "确定");
                return;
            }

            // 显示组选择窗口
            ShowGroupSelectionWindow(selectedPrefabs);
        }

        private static void CreateAddressablesSettings()
        {
            // 创建Addressables设置
            var settings = ScriptableObject.CreateInstance<AddressableAssetSettings>();
            if (settings != null)
            {
                // 设置配置
                settings.name = "AddressableAssetSettings";

                // 确保目录存在
                if (!AssetDatabase.IsValidFolder("Assets/AddressableAssetsData"))
                {
                    AssetDatabase.CreateFolder("Assets", "AddressableAssetsData");
                }

                // 保存设置
                AssetDatabase.CreateAsset(settings, "Assets/AddressableAssetsData/AddressableAssetSettings.asset");
                AssetDatabase.SaveAssets();

                Debug.Log("Addressables设置创建成功");
            }
            else
            {
                Debug.LogError("Addressables设置创建失败");
            }
        }

        // [MenuItem("Assets/Addressables/Add Prefab and Dependencies to Group(添加到组)", true)]
        [MenuItem("Assets/Addressables/添加到组", true)]
        public static bool ValidateAddPrefabAndDependenciesToGroup()
        {
            return GetSelectedPrefabs().Count > 0;
        }

        // [MenuItem("Assets/Addressables/Analyze Dependencies(依赖分析)", false, 31)]
        [MenuItem("Assets/Addressables/依赖分析", false, 31)]
        public static void AnalyzeDependencies()
        {
            var selectedPrefabs = GetSelectedPrefabs();
            if (selectedPrefabs.Count == 0)
            {
                EditorUtility.DisplayDialog("提示", "请选中一个或多个Prefab", "确定");
                return;
            }

            // 打开分析窗口
            PrefabDependencyWindow.ShowWindow();
        }

        [MenuItem("Assets/Addressables/Analyze Dependencies(依赖分析)", true)]
        public static bool ValidateAnalyzeDependencies()
        {
            return GetSelectedPrefabs().Count > 0;
        }

        /// <summary>
        /// 获取选中的Prefab
        /// </summary>
        /// <returns>选中的Prefab列表</returns>
        private static List<GameObject> GetSelectedPrefabs()
        {
            var selectedPrefabs = new List<GameObject>();

            foreach (var obj in Selection.objects)
            {
                if (obj is GameObject gameObject)
                {
                    // 检查是否是Prefab
                    var prefabType = PrefabUtility.GetPrefabAssetType(gameObject);
                    if (prefabType != PrefabAssetType.NotAPrefab)
                    {
                        selectedPrefabs.Add(gameObject);
                    }
                }
            }

            return selectedPrefabs;
        }

        /// <summary>
        /// 显示组选择窗口
        /// </summary>
        /// <param name="prefabs">要处理的Prefab列表</param>
        private static void ShowGroupSelectionWindow(List<GameObject> prefabs)
        {
            var window = ScriptableObject.CreateInstance<GroupSelectionWindow>();
            window.Initialize(prefabs);
            window.position = new Rect(Screen.width / 2, Screen.height / 2, 400, 200);
            window.ShowUtility();
        }

        /// <summary>
        /// 组选择窗口
        /// </summary>
        private class GroupSelectionWindow : EditorWindow
        {
            private List<GameObject> prefabs;
            private string groupName = "PrefabDependencies";
            private Vector2 scrollPos;

            public void Initialize(List<GameObject> prefabList)
            {
                prefabs = prefabList;
                titleContent = new GUIContent("选择Addressables组");
            }

            private void OnGUI()
            {
                GUILayout.Space(10);

                EditorGUILayout.LabelField("将以下Prefab及其依赖添加到Addressables组:", EditorStyles.boldLabel);
                EditorGUILayout.Space();

                // 显示选中的Prefab
                scrollPos = EditorGUILayout.BeginScrollView(scrollPos, GUILayout.Height(60));
                foreach (var prefab in prefabs)
                {
                    EditorGUILayout.LabelField(prefab.name);
                }

                EditorGUILayout.EndScrollView();

                EditorGUILayout.Space();

                // 组名输入
                groupName = EditorGUILayout.TextField("组名", groupName);

                // 现有组选择
                var groupNames = AddressablesGroupManager.GetAllGroupNames();
                if (groupNames.Count > 0)
                {
                    EditorGUILayout.LabelField("现有组:");
                    foreach (var name in groupNames)
                    {
                        if (GUILayout.Button(name, EditorStyles.miniButton))
                        {
                            groupName = name;
                        }
                    }
                }

                EditorGUILayout.Space();

                // 操作按钮
                EditorGUILayout.BeginHorizontal();

                if (GUILayout.Button("取消"))
                {
                    Close();
                }

                GUI.enabled = !string.IsNullOrEmpty(groupName);
                if (GUILayout.Button("确定"))
                {
                    ProcessPrefabs();
                    Close();
                }

                GUI.enabled = true;

                EditorGUILayout.EndHorizontal();
            }

            private void ProcessPrefabs()
            {
                if (prefabs == null || prefabs.Count == 0) return;

                // 分析所有依赖
                var dependencies = DependencyAnalyzer.GetDependencies(prefabs);

                if (dependencies.Count == 0)
                {
                    EditorUtility.DisplayDialog("提示", "没有找到依赖资源", "确定");
                    return;
                }

                // 确认对话框
                if (!EditorUtility.DisplayDialog("确认", $"确定要将 {dependencies.Count} 个资源添加到组 '{groupName}' 吗？", "确定", "取消"))
                {
                    return;
                }

                // 添加到组
                int successCount = AddressablesGroupManager.AddAssetsToGroup(dependencies, groupName);

                // 保存设置
                AssetDatabase.SaveAssets();

                // 显示结果
                if (successCount > 0)
                {
                    EditorUtility.DisplayDialog("完成", $"成功添加 {successCount} 个资源到组 '{groupName}'", "确定");
                }
                else
                {
                    EditorUtility.DisplayDialog("错误", "添加资源失败", "确定");
                }
            }
        }
    }
}